package com.effectiv.req1.email;

import java.util.List;

import jodd.mail.Email;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpServer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class EmailOperationTemplate {

	@Autowired
	private SmtpServer smtpServer;

	@Autowired
	@Qualifier("emailTemplateEngine")
	private TemplateEngine templateEngine;

	@Value("${email.stop}")
	private boolean emailStop;

	@Async
	public void send(Email email) {

		if (!emailStop) {

			SendMailSession session = smtpServer.createSession();
			session.open();
			log.info("Sending email started.");
			session.sendMail(email);
			log.info("Send email.");
			session.close();
			log.info("End email session.");

		}
	}

	@Async
	public void send(Email email, EmailBodyPreparer<?> emailBodyPreparer) {

		email.addHtml(emailBodyPreparer.prepareFromTemplate(templateEngine),
				"UTF-8");
		send(email);
	}

	@Async
	public void send(List<Email> emails) {
		SendMailSession session = smtpServer.createSession();
		session.open();

		for (Email email : emails) {
			session.sendMail(email);
		}

		session.close();
	}

}
